package com.hhc.t;

/**
 * 描述
 * 给定一个节点数为n的无序单链表，对其按升序排序。
 *
 * 数据范围：0<n≤1000000<n≤100000，保证节点权值在[−109,109][−109,109]之内。
 * 要求：空间复杂度 O(n)
 * 示例1
 * 输入：[1,3,2,4,5]
 * 返回值：{1,2,3,4,5}
 * 示例2
 * 输入：[-1,0,-2]
 * 返回值：{-2,-1,0}
 *
 */

public class T {

    public ListNode sortList(ListNode head){
        return sortList(head, null);
    }

    public ListNode sortList(ListNode head, ListNode tail){
        if(head == null){
            return head;
        }

        if(head.next == tail){
            head.next = null;
            return head;
        }

        // 快慢指针找到链表的中点
        ListNode slow = head, fast = head;
        while(fast != tail){
            slow = slow.next;
            fast = fast.next;
            if(fast != tail){
                fast = fast.next;

            }
        }

        ListNode mid = slow;
        ListNode list1 = sortList(head, mid);
        ListNode list2 = sortList(mid, tail);
        // 对两个子链表分别进行排序
        ListNode sorted = sortList(list1, list2);
        return sorted;

    }

    // 合并两个子链表
    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dyHead = new ListNode(0);
        ListNode temp = dyHead, temp1 = head1, temp2 = head2;
        while (temp1 != null && temp2 != null) {
            if (temp1.val <= temp2.val) {
                temp.next = temp1;
                temp1 = temp1.next;
            } else {
                temp.next = temp2;
                temp2 = temp2.next;
            }
            temp = temp.next;
        }
        if (temp1 != null) {
            temp.next = temp1;
        } else if (temp2 != null) {
            temp.next = temp2;
        }
        return dyHead.next;
    }

}
